package com.stone.zeus.component.grpc.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

/**
 * @author fujianjian
 * @date 2023/3/1 11:38
 **/
@RequiredArgsConstructor
public class ZeusNacosServiceDiscovery {

    private final NacosDiscoveryProperties discoveryProperties;
    private final NacosServiceManager nacosServiceManager;
    private final String extraGroup;

    public List<String> getServices() throws NacosException {
        String group = discoveryProperties.getGroup();
        ListView<String> defultList = namingService().getServicesOfServer(1, Integer.MAX_VALUE, group);
        ListView<String> extraList = namingService().getServicesOfServer(1, Integer.MAX_VALUE, extraGroup);
        List<String> retData = defultList.getData();
        for (String datum : extraList.getData()) {
            if (retData.contains(datum)) {
                continue;
            }
            retData.add(datum);
        }
        return retData;
    }

    public List<ServiceInstance> getInstances(String serviceId) throws NacosException {
        String group = discoveryProperties.getGroup();
        List<Instance> instances = namingService().selectInstances(serviceId, group, true);
        instances.addAll(namingService().selectInstances(serviceId, extraGroup, true));
        return NacosServiceDiscovery.hostToServiceInstanceList(instances, serviceId);
    }

    private NamingService namingService() {
        return nacosServiceManager.getNamingService(discoveryProperties.getNacosProperties());
    }
}
